package com.gears_software.bbnetwork.activitys;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.WindowFeature;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.StaticLayout;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.avos.avoscloud.AVAnalytics;
import com.gears_software.bbnetwork.R;
import com.gears_software.bbnetwork.datas.finders.IBBNetworkFinder;
import com.gears_software.bbnetwork.datas.finders.ProjectUrl;
import com.gears_software.bbnetwork.datas.finders.impl.IBBNetworkFinderImpl;
import com.gears_software.bbnetwork.datas.models.BaseJsonToModel;
import com.gears_software.bbnetwork.datas.models.CertificationModel;
import com.gears_software.bbnetwork.datas.models.IdentityImageModel;
import com.gears_software.bbnetwork.datas.models.ResultModel;
import com.gears_software.bbnetwork.datas.models.ReturnCode;
import com.gears_software.bbnetwork.dialogs.DeleteDialog;
import com.gears_software.bbnetwork.dialogs.DeleteDialog.ISetOnClick;
import com.gears_software.bbnetwork.utlis.ActivityUtils;
import com.gears_software.bbnetwork.utlis.BBNetworkSharedPref_;
import com.gears_software.bbnetwork.utlis.CommonUtils;
import com.gears_software.bbnetwork.utlis.ToastUI;
import com.gears_software.common.io.FileUtils;
import com.gears_software.common.net.NetworkUtil;
import com.gears_software.common.net.avatarupload.UploadFileUtil;
import com.gears_software.common.utils.setHeaderImage.HeaderImageUtil;
import com.gears_software.common.utils.setHeaderImage.HeaderImageUtil.OnGetBitmap;

/**
 * 我的信息
 * 
 * @author DY-PC
 * 
 */
@EActivity(R.layout.activity_myinfo)
@WindowFeature(Window.FEATURE_NO_TITLE)
public class MyInfoActivity extends Activity {

	HeaderImageUtil imageUtil;

	@ViewById
	ImageView image_touxiang1;// 图片一

	@ViewById
	ImageView image_touxiang2;// 图片二

	@ViewById
	EditText edit_auth_name;// 姓名

	@ViewById
	EditText edit_company;// 公司

	@ViewById
	EditText edit_number;// 身份证号

	@ViewById
	RelativeLayout audit_defailt;// 没有提交状态

	@ViewById
	RelativeLayout audit_zhong;// 审核中

	@ViewById
	RelativeLayout audit_notpass;// 审核未通过

	@ViewById
	RelativeLayout audit_pass;// 通过审核
	
	@ViewById
	TextView text_phone;//电话号吗
	
	@ViewById
	TextView text_submit;//提交
	
	List<IdentityImageModel> listImage = new ArrayList<IdentityImageModel>();//图片信息

	@Pref
	BBNetworkSharedPref_ sp;

	@Bean(IBBNetworkFinderImpl.class)
	IBBNetworkFinder finder;

	@Bean
	ProjectUrl url;

	@Bean
	ToastUI toast;

	private int setImage = -1;

	@AfterViews
	void onCreate() {
		text_phone.setText(sp.phone().get());
		imageUtil = new HeaderImageUtil(this);
		imageUtil.setZoom(false);
		imageUtil.setOnGetBitmap(new OnGetBitmap() {
			@Override
			public void getBitmap(Bitmap bitmap) {
				// 监听到的bitmap图片值
				uploadHeaderImage(bitmap);
			}
		});
		initInfo();
	}

	@Background
	void initInfo() {
		ResultModel<CertificationModel> res = finder.getRealNameAuth(sp
				.userId().get());
		if (res.getReturnCode().equals(ReturnCode.SUCCEED)) {
			initView(res.getResObj());
		} else {
			showTxt("信息读取错误！" + res.getMessage());
		}
	}

	@UiThread
	void initView(CertificationModel model) {

		if (model != null) {
			if(model.getStatus()!=null){
				if (model.getStatus().equals("0")) {
					audit_defailt.setVisibility(View.VISIBLE);
					text_submit.setVisibility(View.VISIBLE);
				}
				if (model.getStatus().equals("1")) {
					audit_zhong.setVisibility(View.VISIBLE);
					text_submit.setVisibility(View.GONE);
				}
				if (model.getStatus().equals("2")) {
					audit_pass.setVisibility(View.VISIBLE);
					sp.status().put("2");
					text_submit.setVisibility(View.GONE);
				}
				if (model.getStatus().equals("3")) {
					audit_notpass.setVisibility(View.VISIBLE);
					text_submit.setVisibility(View.VISIBLE);
				}
			}
			if (model.getRealName() != null) {
				edit_auth_name.setText(model.getRealName());
				if (model.getStatus().equals("1")
						|| model.getStatus().equals("2")) {
					edit_auth_name.setEnabled(false);
				}
			}
			if (model.getCompany() != null) {
				edit_company.setText(model.getCompany());
				if (model.getStatus().equals("1")
						|| model.getStatus().equals("2")) {
					edit_company.setEnabled(false);
				}
			}
			if (model.getIDCardNo() != null) {
				edit_number.setText(model.getIDCardNo());
				if (model.getStatus().equals("1")
						|| model.getStatus().equals("2")) {
					edit_number.setEnabled(false);
				}
			}

			// 图片展示
			listImage = model.getAttachments();
			if (listImage != null && listImage.size() > 0) {
				for (int i = 0; i < listImage.size(); i++) {
					IdentityImageModel imgModel = listImage.get(i);
					if (i == 0) {
						showImage(imgModel.getThumbnailFileInformationUrl(), image_touxiang1);
						if (model.getStatus().equals("1")
								|| model.getStatus().equals("2")) {
							image_touxiang1.setClickable(false);
						}
						image_touxiang1.setTag("1");//标记该图片为读取的数据
					}
					if (i == 1) {
						showImage(imgModel.getThumbnailFileInformationUrl(), image_touxiang2);
						if (model.getStatus().equals("1")
								|| model.getStatus().equals("2")) {
							image_touxiang2.setClickable(false);
						}
						image_touxiang2.setTag("1");
					}
				}
			}
		}
	}
	
	@Background
	void showImage(String url,ImageView imageview){
		Bitmap bitmap = UploadFileUtil.httpsGetBitmap(url);
		showImageView(imageview, bitmap);
	}
	
	@UiThread
	void showImageView(ImageView imageview,Bitmap bitmap){
		imageview.setImageBitmap(bitmap);
	}

	// 头像上传方法
	@Background
	void uploadHeaderImage(Bitmap bitmap) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		InputStream isbm = new ByteArrayInputStream(out.toByteArray());
		File tempFile = new File(Environment.getExternalStorageDirectory()
				+ "/" + HeaderImageUtil.IMAGE_FILE_NAME);
		FileUtils.writeFile(tempFile, isbm);

		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", sp.userId().get());
		Map<String, File> fileMap = new HashMap<String, File>();
		fileMap.put(tempFile.getName(), tempFile);

		try {
			String json = UploadFileUtil.post(url.getUpdateFile(), params,
					fileMap);
			if (json == null) {
				showTxt("头像上传失败");
				return;
			}
			BaseJsonToModel jsonModel = JSON.parseObject(json,
					BaseJsonToModel.class);
			if(jsonModel.getReturnData()!=null){
				IdentityImageModel model = JSON.parseObject(jsonModel.getReturnData().toString(),IdentityImageModel.class);
				listImage.add(model);
			}
			if (jsonModel.getResultCode().equals(ReturnCode.SUCCEED)) {
				SetImage(bitmap);
			} else {
				showTxt("上传失败！" + jsonModel.getResultMessage());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@UiThread
	void SetImage(Bitmap bitmap) {
		if (setImage == 1) {
			image_touxiang1.setImageBitmap(bitmap);
			image_touxiang1.setTag("1");
		} else {
			image_touxiang2.setImageBitmap(bitmap);
			image_touxiang2.setTag("1");
		}
	}

	DeleteDialog deleteDialog = null;
	// 图片1
	@Click
	void image_touxiang1() {
		boolean isnet = NetworkUtil.checkNetworkInfo(this);
		if(!isnet){
			showTxt("请检查网络是否正常！");
			return;
		}
		setImage = 1;
		String type = (String) image_touxiang1.getTag();
		if(type!=null&&type.equals("1")){
			deleteDialog = new DeleteDialog(this, R.style.MyDialog);
			deleteDialog.setOnClick(new ISetOnClick() {
				@Override
				public void returnCode(int type) {
					if(type==1){
						if(listImage!=null&&listImage.size()>0){
							IdentityImageModel identity = listImage.get(0);
							DeleteImage(identity, image_touxiang1);
						}
					}
					if(type==2){
						deleteDialog.dismiss();
					}
				}
			});
			deleteDialog.show();
		}else{
			imageUtil.showDialog();
		}
	}
	
	//删除文件方法
	@Background
	void DeleteImage(IdentityImageModel model,ImageView imageView){
		ResultModel<String> res = finder.getDeleteFile(sp.userId().get(), model.getOriginalFileInformationId());
		if(res.getReturnCode().equals(ReturnCode.SUCCEED)){
			updateView(model,imageView);
		}else{
			showTxt("删除失败！"+res.getMessage());
		}
	}
	
	//删除成功后操作
	@UiThread
	void updateView(IdentityImageModel model,ImageView imageView){
		imageView.setTag("0");
		imageView.setImageResource(R.drawable.jiahao);
		if(listImage!=null){
			listImage.remove(model);
		}
		deleteDialog.dismiss();
	}
	

	// 图片2
	@Click
	void image_touxiang2() {
		boolean isnet = NetworkUtil.checkNetworkInfo(this);
		if(!isnet){
			showTxt("请检查网络是否正常！");
			return;
		}
		setImage = 2;
		String type = (String) image_touxiang2.getTag();
		if(type!=null&&type.equals("1")){
			deleteDialog = new DeleteDialog(this, R.style.MyDialog);
			deleteDialog.setOnClick(new ISetOnClick() {
				@Override
				public void returnCode(int type) {
					if(type==1){
						if(listImage!=null&&listImage.size()>0){
							IdentityImageModel identity = listImage.get(0);
							DeleteImage(identity, image_touxiang2);
						}
					}
					if(type==2){
						deleteDialog.dismiss();
					}
				}
			});
			deleteDialog.show();
		}else{
			imageUtil.showDialog();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		imageUtil.onResultActiivty(requestCode, resultCode, data);// 在onactivityResult中调用此方法。
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		AVAnalytics.onResume(this);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AVAnalytics.onPause(this);
	}
	
	@UiThread
	void showTxt(String txt) {
		toast.ShowToast(txt);
	}
	
	//后退
	@Click
	void image_back(){
		finish();
	}
	
	//提交按钮
	@Click
	void text_submit(){
		boolean isnet = NetworkUtil.checkNetworkInfo(this);
		if(!isnet){
			showTxt("请检查网络是否正常！");
			return;
		}
		String realName = edit_auth_name.getText().toString();
		String company = edit_company.getText().toString();
		String IDCardNo = edit_number.getText().toString();
		if(realName==null||realName.equals("")){
			showTxt("请输入姓名！");
			return;
		}
		if(company==null||company.equals("")){
			showTxt("请输入公司名称！");
			return;
		}
		if(IDCardNo==null||IDCardNo.equals("")){
			showTxt("请输入身份证号！");
			return;
		}
		
		boolean isShen = CommonUtils.isShenfen(IDCardNo);
		if(!isShen){
			showTxt("身份证格式不正确！");
			return;
		}
		audit(realName, company, IDCardNo);
	}
	
	//认证请求
	@Background
	void audit(String realName,String company,String IDCardNo){
		ResultModel<String> res = finder.getAudit(sp.userId().get(), realName, company, IDCardNo);
		if(res.getReturnCode().equals(ReturnCode.SUCCEED)){
			showTxt("认证请求提交成功！");
			finish();
		}else{
			showTxt(res.getMessage());
		}
	}
	
	
	@Click
	void txt_defaile(){
		Intent intent = new Intent(this,UpFileDefaileActivity_.class);
		startActivity(intent);
	}
	
	//退出登录
	@Click
	void btn_quit(){
		ActivityUtils.closeActivity();
		sp.phone().put("");
		Intent intent = new Intent(this,LoginActivity_.class);
		startActivity(intent);
		finish();
	}
	
}
